//
//  ResetPasswordViewController.m
//  KiklinkApp
//
//  Created by LF on 14/10/22.
//  Copyright (c) 2014年 Kiklink. All rights reserved.
//

#import "ResetPasswordViewController.h"
#import "API.h"

@interface ResetPasswordViewController ()
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *verificationCodeTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *repeatPasswordTextField;
@property (strong, nonatomic) IBOutlet UIView *backgroundView;

@end

@implementation ResetPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	UITapGestureRecognizer *backgroundTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard)];
	[self.backgroundView addGestureRecognizer:backgroundTapRecognizer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)onClickGetVerificationCode:(id)sender {
	
	if (! [AccountManager isPhoneNumberValid:self.phoneNumberTextField.text]) {
		showAlert(@"手机号格式不正确");
		return;
	}
	
	[AccountManager sendVerificationCodeTo:self.phoneNumberTextField.text];
}

- (IBAction)onClickResetPassword:(id)sender {
	if (! [AccountManager isVerificationCodeValid:self.verificationCodeTextField.text]) {
		showAlert(@"验证码不正确");
		return;
	}
	
	if (! [AccountManager isPasswordValid:self.passwordTextField.text]) {
		showAlert(@"密码过短");
		return;
	}
	
	if (! [self.passwordTextField.text isEqualToString:self.repeatPasswordTextField.text]) {
		showAlert(@"密码不一致");
		return;
	}
	
	[API resetPasswordWithPhoneNumber:self.phoneNumberTextField.text verificationCode:self.verificationCodeTextField.text password:self.passwordTextField.text Callback:^(int stateCode, NSString *word, id content) {
		
		if(stateCode == FAILURE_RETURN_ERRER_CODE)
		{
			showAlert(word);
			return;
		}
		else if(stateCode < 0)
		{
			showAlert(@"重置密码失败");
			return;
		}
		else
		{
			showAlert(@"重置密码成功，请重新登录");
			[self.navigationController popViewControllerAnimated:YES];
		}

	}];
}

-(void)closeKeyboard
{
	[self.phoneNumberTextField resignFirstResponder];
	[self.verificationCodeTextField resignFirstResponder];
	[self.passwordTextField resignFirstResponder];
	[self.repeatPasswordTextField resignFirstResponder];
}

@end
